﻿using System.Collections.Generic;
using Didaku.QEngine.Common.Entities;
using Didaku.QEngine.Common.Extensions;
using Didaku.QEngine.Common.Interfaces.Engine;
using Didaku.QEngine.Common.Wrapper.Engine;

namespace Didaku.QEngine.Methods.Assign
{
    internal class SpecifyCall : IAssignFunc<string>
    {
        #region Implementation of ICallFunc<string>

        /// <summary>发起呼叫(提取交易)的柜台
        /// </summary>
        /// <value>The counter.</value>
        /// <remarks></remarks>
        public Counter Counter { get; set; }

        /// <summary>发起呼叫(提取交易)的员工
        /// </summary>
        /// <value>
        /// The staff.
        /// </value>
        public Staff Staff { get; set; }

        /// <summary>被指定的号码，未考虑大小写，请在调用时考虑
        /// </summary>
        /// <value>The params.</value>
        /// <remarks></remarks>
        public string Condition { get; set; }

        /// <summary>从一个柜台的服务逻辑中获取交易的方法
        /// </summary>
        /// <returns></returns>
        public bool Execute(out Transaction transaction, ServiceLogic logic, ICollection<ServiceQueue> queues)
        {
            if (!string.IsNullOrWhiteSpace(Condition))
            {
                foreach (ServiceQueue queue in queues) //查找所有的队列
                {
                    bool isBackCall;
                    if (TryGet(out transaction, out isBackCall, queue))
                    {
                        if (isBackCall)
                            logic.GetSuperQueue().Add(transaction);
                        return true;
                    }
                }
            }
            transaction = null; //指定呼叫的号码在队列中及队列的历史中均不存在
            return false;
        }

        /// <summary>从一个队列中获取交易的方法
        /// </summary>
        private bool TryGet(out Transaction transaction, out bool isBackCall, ServiceQueue queue)
        {
            //优先
            if (queue.TrySearchRunning(Condition, out transaction))
            {
                isBackCall = false;
                return true;
            }
            //回呼
            if (queue.TrySearchClosed(Condition, out transaction))
            {
                isBackCall = true;
                return true;
            }
            isBackCall = false;
            return false;
        }

        #endregion
    }
}